<template>
	<view>
		<view class="uni-common-mt">
			<view class="uni-list">
				<view class="uni-list-cell">
					<view class="uni-list-cell-left">
						<view class="uni-label">图片类型</view>
					</view>
					<view class="uni-list-cell-right">
						<picker :range="imageTypes" @change="imageTypeSeleced" :value="imageTypeIndex" mode="selector">
							<view class="uni-input">{{imageTypes[imageTypeIndex]}}</view>
						</picker>
					</view>
				</view>
				
				<view class="uni-list-cell cell-pd">
					<view class="uni-uploader">
						<view class="uni-uploader-head uni-uploader-head-cell-pd">
							<view class="uni-uploader-title">图片</view>
							<view class="uni-uploader-info">{{addItemImageData.images.length}}/9</view>
						</view>
						<view class="uni-uploader-body">
							<view class="uni-uploader__files">
								<block v-for="(image,index) in showImage" :key="index">
									<view class="uni-uploader__file">
										<image class="uni-uploader__img" :src="image" :data-src="image" @tap="previewImage"></image>
									</view>
								</block>
								<view class="uni-uploader__input-box" v-if="addItemImageData.images.length < 9">
									<view class="uni-uploader__input" @tap="chooseImage"></view>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<view class="button-sp-area">
					<button :disabled="!(addItemImageData.images.length > 0 && !imageUpload)" type="primary" plain="true" @click="projectItemImageSubmit">提交</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { addProjectItemImage } from '@/api/projectItemImage.js'
	import { uploadProjectItemImage } from '@/api/uploadFile.js'
	import permision from "@/common/permission.js"
	
	export default {
		onLoad(options){
			if(!options || !options.id) {
				uni.navigateBack({delta:1});
				return;
			}
			this.addItemImageData.itemId = decodeURIComponent(options.id);
			if(options.type) {
				this.addItemImageData.imageType = decodeURIComponent(options.type);
				this.imageTypeIndex = decodeURIComponent(options.type) - 1;
			}
			else {
				this.addItemImageData.imageType = 1;
				this.imageTypeIndex = 0;
			}
		},
		data() {
			return {
				imageTypes: ["凭据照片", "实际照片"],
				imageTypeIndex: 0,
				showImage: [],
				addItemImageData: {
					itemId: undefined,
					images: [],
					imageType: undefined,
				},
				imageUpload: false,
			}
		},
		methods: {
			imageTypeSeleced(e) {
				this.imageTypeIndex = e.detail.value;
				this.addItemImageData.imageType = e.detail.value + 1;
			},
			
			// 图片上传相关
			chooseImage: async function(type) {
				if(this.imageUpload) {
					return;
				}
				
				// 判断是否有相关的权限
				let status = await this.checkPermission();
				if (status !== 1) {
					return;
				}
				uni.chooseImage({
					sourceType: ['album'],
					sizeType: ['original'],
					count: 9 - this.addItemImageData.images.length,
					success: (res) => {
						new Promise(async(resolve, reject) => {
							uni.showToast({
								title: "图片上传中",
								duration: 2147483647,
								icon: "loading"
							});
							this.imageUpload = true;
							for(var i = 0; i < res.tempFilePaths.length; i++) {
								var image = res.tempFilePaths[i];
								await uploadProjectItemImage(image).then(resp => {
									this.addItemImageData.images.push(resp.datas)
									this.showImage.push(image)
								})
								.catch(error => {
									console.log(error);
								});
								await this.$sleep(600) 
							}
							return resolve();
						})
						.then(() => {
							uni.hideToast();
							this.imageUpload = false;
						})
						.catch(error => {
							uni.showToast({
								title: "图片上传失败，" + error,
								duration: 2000,
								icon: "none"
							});
							uni.hideToast();
							this.imageUpload = false;
						});
					}
				})
			},
			
			// 图片全屏查看
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.showImage
				})
			},
			
			// 检查设备权限
			async checkPermission() {
				let status = permision.isIOS 
					? await permision.requestIOS('album') 
					: await permision.requestAndroid('android.permission.READ_EXTERNAL_STORAGE');
			
				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}
				return status;
			},
			
			projectItemImageSubmit() {
				if(this.addItemImageData.images.count <= 0) {
					uni.showToast({
						title: "请提交图片",
						icon: 'none',
						duration: 1000
					});
					return;
				}
				addProjectItemImage(this.addItemImageData).then(resp => {
					uni.showToast({
						title: "增加成功",
						icon: 'none',
						duration: 1000
					});
					uni.navigateBack({delta:1});
				})
				.catch(error => {
					uni.showToast({
						title: error,
						icon: 'none',
						duration: 1000
					})
				});
			}
		}
	}
</script>

<style>
	.cell-pd {
		padding: 22rpx 30rpx;
	}

	.uni-uploader-head-cell-pd {
		margin-left: 22rpx;
	}
	
    .button-sp-area {
        margin: 30rpx auto;
        width: 80%;
    }
</style>

